#import "BluetoothCenter.h"
#import "MBProgressHUD+Add.h"
#import "UICKeyChainStore.h"
#import "NSData+TF_Encrypt.h"
#import "TempTarget.h"
#import "LBTool.h"
#import "LBHud.h"
#import "BluetoothCenter+Tips.h"


#define DeviceToken @"DeviceToken"////四个字节的token,存储的是NSData
#define AES_KEY @"aes_key"//aes密钥
@interface BluetoothCenter ()<CBCentralManagerDelegate, CBPeripheralDelegate>
{
    NSTimer *readRSIIAndBatteryTimer;//读取电量和信号
    NSTimer *_disconnectTimer;
    NSMutableArray *connectedPh;
    opSucess _autoConSuc;
    opFail _autoConFail;
    //NSTimer *searchTimer;
    int connectCount;//连接设备定时器计时
}

@property (strong, nonatomic) NSMutableArray<NSUUID *> *peripheralUUIDs;
@property (nonatomic, strong) CBPeripheral *disconnectPeripheral;//断开的外设
@property (nonatomic, strong) CBPeripheral *reConePeripheral;//重连的外设
@property(nonatomic,strong)NSTimer *connectTimer;//连接设备定时器
@end
@implementation BluetoothCenter
-(BOOL)isConnectPeripheral{
    return self.connectSuccessPeripherals.count>0;
}
+ (instancetype)shareInstance {
    static BluetoothCenter *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
        
    });
    return _instance;
}
- (instancetype)init {
    if (self = [super init]) {
        self.writeCharacteristics = @"6E400002-B5A3-F393-E0A9-E50E24DCCA9E";
        _deviceType = DeviceTypeBeacon;
        _sendNumber = 0;
        connectCount = 0;
        //加上了恢复sf这个app杀死了蓝牙也会连着
        self.deviceInfo = [[NSMutableDictionary alloc]init];
        self.rssi_filter = -80;
        self.majorMin_filter = 0;
        self.majorMax_filter = 65535;
        self.minorMin_filter = 0;
        self.minorMax_filter = 65535;
        //options:@{CBCentralManagerOptionRestoreIdentifierKey: @"JingCaiNewBluetoothRestoreIdentifierKey"}
        self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() ];
        self.connectSuccessPeripherals = [NSMutableArray new];
        self.isReadValueC = NO;
        self.readValueC = @"";
    }
    return self;
}
#pragma mark --------- 蓝牙状态发生了变化 --------------
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
    switch (central.state) {
        case CBManagerStateUnknown:
        {
            NSLog(@"**************蓝牙设备状态发生了改变:未知原因**************");
            break;
        }
        case CBManagerStateResetting:
        {
            NSLog(@"**************蓝牙设备状态发生了改变:重置中...**************");
            break;
        }
        case CBManagerStateUnsupported:
        {
            NSLog(@"**************蓝牙设备状态发生了改变:不支持设备**************");
            break;
        }
        case CBManagerStateUnauthorized:
        {
        NSLog(@"**************蓝牙设备状态发生了改变:未授权**************");
            break;
        }
        case CBManagerStatePoweredOff:
        {
        NSLog(@"**************蓝牙设备状态发生了改变:关闭了蓝牙**************");
            [self stopDisconnectTimer];
            [[NSNotificationCenter defaultCenter] postNotificationName:BluetoochStatusChange object:nil];
            
            self.isBluetoothOpen = NO;
            self.isConnectPeripheral = NO;
            self.currentPeripheral = nil;
            [self.connectSuccessPeripherals removeAllObjects];
            if (_peripheralBlk) {
                _peripheralBlk(_connectSuccessPeripherals);
            }
            break;
        }
        case CBManagerStatePoweredOn:
        {
            NSLog(@"**************蓝牙设备状态发生了改变:打开了蓝牙**************");
            self.isBluetoothOpen = YES;
            //[self startReConnectTimer];
            //检索设备
            NSArray *uuidArray = [self getSavedReConnectServiceUUIDs];
            [self retrieveConnectPeripheral:uuidArray];
            
            [self scanperipheral];
            [[NSNotificationCenter defaultCenter] postNotificationName:BluetoochStatusOpenChange object:nil];
            break;
        }
        default:
            break;
    }
    
    
}
#pragma mark ------- 扫描外设 --------
- (void)scanperipheral {
    if (self.isBluetoothOpen) {
//        [self startUpdateTimer];
        [self.peripherals removeAllObjects];
        [self.peripheralUUIDs removeAllObjects];
        [self.centralManager stopScan];
        [self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(1)}];
        //NSLog(@"扫描指定的外设:%@",Found_ServiceUUID);
    }
}
#pragma mark ------- 扫描指定的外设 --------
- (void)startScanningPrivate:(NSArray *)uuidStrs {
//    self.isManualDisconnect = NO;
    [self saveScanningUUIDS:uuidStrs];
    NSMutableArray *uuidAry = nil;
    if (uuidStrs.count > 0) {
        uuidAry = [NSMutableArray arrayWithCapacity:uuidStrs.count];
        for (NSString *uuidStr in uuidStrs) {
            [uuidAry addObject:[CBUUID UUIDWithString:uuidStr]];
        }
    }
    //key值是NSNumber,默认值为NO表示不会重复扫描已经发现的设备,如需要不断获取最新的信号强度RSSI所以一般设为YES
    
    [self.centralManager scanForPeripheralsWithServices:uuidAry options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(1)}];
}
#pragma mark --------- 发现设备 ----------
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    if ([RSSI intValue]>0||peripheral.name.length==0) {
        return;
    }
//    if ([peripheral.name containsString:@"Holy"]) {
//            NSLog(@"发现设备:%@ 广播内容:%@  信号强度:%@",peripheral.name,advertisementData,RSSI);
//    }
    //Beacon,iBeacon,eddystone的判断标识
    /*
     manufacturerData 的前三个字节为判断依据
     0x4C0002   iBeacon  02是beacon类型,0x4C00是通用 iBeacon  UUID
     0xFFFF02   Beacon   02是beacon类型,0xFFFF是 Beacon    UUID
     serviceData  UUID为AAFE时代表 第一个字节是FrameType
     */
    //    CC29E966-ED60-531B-E3AD-77D24FC2A8B2
    //DFU 8633084F-6A4E-234A-ABB1-B7D3DB5186C5
//    if ([peripheral.name containsString:@"DFU"]) {
//        NSLog(@"发现设备:%@ 广播内容:%@  信号强度:%@ UUID:%@",peripheral.name,advertisementData,RSSI,peripheral.identifier.UUIDString);
//    }
    if ([advertisementData[@"kCBAdvDataServiceData"] objectForKey:[CBUUID UUIDWithString:@"5242"]]&&(self.deviceType!=DeviceTypeEddystone)) {
        NSData *data = [advertisementData[@"kCBAdvDataServiceData"] objectForKey:[CBUUID UUIDWithString:@"5242"]];
        NSData *flagData = [data subdataWithRange:NSMakeRange(0, 1)];
        Byte *flag_byte = (Byte*)[flagData bytes];
        
        //425241，则表示此蓝牙设备为标准beacon,可进行密码、UUID服务码、MAC地址、major和minor、密码等数据的修改和自定义广播数据的修改
        //因为Beacon和iBeacon  ServiceData 第一字节都是0x41,所以只能拿kCBAdvDataManufacturerData来区分
//        if (!advertisementData[@"kCBAdvDataManufacturerData"]) {
//            return;
//        }
        NSLog(@"发现设备:%@ 广播内容:%@  信号强度:%@",peripheral.name,advertisementData,RSSI);
        NSString *deviceName_str;//蓝牙名称
        NSMutableDictionary *mtbDic ;
        if ([self.deviceInfo objectForKey:peripheral.identifier.UUIDString]) {
            mtbDic = [self.deviceInfo objectForKey:peripheral.identifier.UUIDString];
        }else{
            mtbDic = [NSMutableDictionary new];
        }
        if (advertisementData[@"kCBAdvDataLocalName"]) {
            [mtbDic setObject:advertisementData[@"kCBAdvDataLocalName"] forKey:device_name];
            deviceName_str = [advertisementData[@"kCBAdvDataLocalName"] uppercaseString];
        }else{
            deviceName_str = [peripheral.name uppercaseString];
        }
        
        if (flag_byte[0] == 0x41) {
           
            [mtbDic setObject:deviceName_str forKey:device_name];
            [mtbDic setObject:@"iBeacon" forKey:device_type];
            
        }else{
            [mtbDic setObject:deviceName_str forKey:device_name];
            [mtbDic setObject:@"Unknow" forKey:device_type];
        }
        //信号
        [mtbDic setObject:RSSI forKey:device_rssi];
        
//        if ([peripheral.name containsString:@"Holy"]) {
//                NSLog(@"发现设备:%@ 广播内容:%@  信号强度:%@",peripheral.name,advertisementData,RSSI);
//        }
        //从厂家数据解析Beacon 前面的三个字节为FFFF02  iBeacon:4C0002,但是iBeacon厂家数据看不到
        if (advertisementData[@"kCBAdvDataManufacturerData"]) {
            NSData *data = [[NSData alloc]initWithData: advertisementData[@"kCBAdvDataManufacturerData"]];
            if (data.length>=3) {
                NSData *tagData =  [data subdataWithRange:NSMakeRange(0, 3)];
                Byte tag_byte[] = {0xff,0xff,0x02};
                NSData *data1 = [NSData dataWithBytes:tag_byte length:sizeof(tag_byte)];
                if ([tagData isEqualToData:data1]) {
                    [mtbDic setObject:deviceName_str forKey:device_name];
                    [mtbDic setObject:@"Beacon" forKey:device_type];
                }
            }
            if (data.length==25) {
//                NSLog(@"发现设备:%@ 广播内容:%@  信号强度:%@",peripheral.name,advertisementData,RSSI);
                //beaconUUID
                NSData *beaconData =  [data subdataWithRange:NSMakeRange(4, 16)];
                NSString *beaconStr = [LBTool convertHexDataToHexString:beaconData];
                [mtbDic setObject:beaconStr forKey:device_beacon_uuid];
//                NSLog(@"beacon_UUID:%@",beaconMtbStr);
                
                //major
                NSData *majorData =  [data subdataWithRange:NSMakeRange(20, 2)];
                int majorValue = [LBTool convertHexDataToDecimalism:majorData];
                NSString *major_string = [NSString stringWithFormat:@"%d",majorValue];
                [mtbDic setObject:major_string forKey:device_major];
//                NSLog(@"major:%@",major_string);
                
                //minor
                NSData *minorData =  [data subdataWithRange:NSMakeRange(22, 2)];
                int minorValue = [LBTool convertHexDataToDecimalism:minorData];
                NSString *minor_string = [NSString stringWithFormat:@"%d",minorValue];
                [mtbDic setObject:minor_string forKey:device_minor];
//                NSLog(@"minor:%@",minor_string);
            }
           
        }
        //mac地址在  kCBAdvDataServiceData  中
        if (data.length>=10) {
            //第一个字节是判断位,已在上面开始作了判断  0x41
            //电量
            NSData *batteryData = [data subdataWithRange:NSMakeRange(1, 1)];
            Byte *battery_byte = (Byte*)[batteryData bytes];
            NSString *batteryString = [NSString stringWithFormat:@"%d",(int)battery_byte[0]];
            [mtbDic setObject:batteryString forKey:device_battery];
//                            NSLog(@"--->设备电量:%@",batteryString);
            //mac地址
            NSData *macData = [data subdataWithRange:NSMakeRange(2, 6)];
            Byte *mac_byte = (Byte*)[macData bytes];
            NSMutableString *macMtbString = [NSMutableString new];
            for (int i=0; i<macData.length; i++) {
                NSString *temp = [NSString stringWithFormat:@"%02x:",mac_byte[i]];
                [macMtbString appendString:temp];
            }
//                NSLog(@"--->MAC地址:%@",macMtbString);
            NSString *finalStr = [macMtbString substringToIndex:macMtbString.length-1];
            [mtbDic setObject:[finalStr uppercaseString]forKey:device_mac];
            
            //广播间隔
            NSData *intervalData = [data subdataWithRange:NSMakeRange(8, 1)];
            Byte *interval_byte = (Byte*)[intervalData bytes];
            NSString *intervalString = [NSString stringWithFormat:@"%d",(int)interval_byte[0]];
            [mtbDic setObject:intervalString forKey:device_interval];
//                NSLog(@"--->广播间隔:%@",intervalString);
            //发射功率
            NSData *txPowerData = [data subdataWithRange:NSMakeRange(9, 1)];
            Byte *txPower_byte = (Byte*)[txPowerData bytes];
            NSString *txPowerString = [NSString stringWithFormat:@"%d",(int)txPower_byte[0]];
            [mtbDic setObject:txPowerString forKey:device_tx_power];
//                NSLog(@"--->发射功率:%@",txPowerString);
            
            //以下是后面增加的3个字节
            if (data.length>=13) {
                //标志位
                NSData *judeData = [data subdataWithRange:NSMakeRange(10, 1)];
                Byte *jude_byte = (Byte*)[judeData bytes];
                
                //温度
                if (jude_byte[0]==0x01) {
                    //整数部分(有符号字符类型)
                    NSData *integer_data = [data subdataWithRange:NSMakeRange(11, 1)];
                    Byte *integer_byte = (Byte*)[integer_data bytes];
                    NSString *hexStr = [NSString stringWithFormat:@"%x",integer_byte[0]];
                    int sign_value = [LBTool convertSignedHexStrToInt:hexStr];
                    
                    
                    //小数部分(无符号字符类型)
                    NSData *decimal_data = [data subdataWithRange:NSMakeRange(12, 1)];
                    Byte *decimal_byte = (Byte*)[decimal_data bytes];
                    NSString *decimal_string = [NSString stringWithFormat:@"%x",decimal_byte[0]];
                    unsigned int outVal;
                    NSScanner* scanner = [NSScanner scannerWithString:decimal_string];
                    [scanner scanHexInt:&outVal];
                    NSString *temp = [NSString stringWithFormat:@"%d.%d",sign_value,outVal];
                    [mtbDic setObject:temp forKey:device_temperature];
//                    NSLog(@"--->温度:%@",temp);
                }
                //气压
                if (jude_byte[0]==0x02) {
                    NSData *pressure_data = [data subdataWithRange:NSMakeRange(11, 2)];
                   int  pressure_int = [LBTool convertHexDataToDecimalism:pressure_data]+80000;
                    [mtbDic setObject:@(pressure_int) forKey:device_pressure];
//                    NSLog(@"--->气压:%dPa",pressure_int);
                }
                //湿度
                if (jude_byte[0]==0x03) {
                    NSData *humidity_data = [data subdataWithRange:NSMakeRange(11,1)];
                    int humidity_int = [LBTool convertHexDataToDecimalism:humidity_data];
                   // [humidity_data getBytes:&humidity_int length:sizeof(humidity_int)];
                    [mtbDic setObject:@(humidity_int) forKey:device_humidity];
//                    NSLog(@"--->湿度:%d",humidity_int);
                }
                //20秒内是否有振动
                if (jude_byte[0]==0x04) {
                    NSData *shake_data = [data subdataWithRange:NSMakeRange(11, 1)];
                    Byte *shake_byte = (Byte*)[shake_data bytes];
                    [mtbDic setObject:@(shake_byte[0]) forKey:device_shake];
//                    NSLog(@"--->20秒是否有振动:%d",shake_byte[0]);
                    
                }
                //朝向
                if (jude_byte[0]==0x05) {
                    NSData *direction_data = [data subdataWithRange:NSMakeRange(11, 1)];
                    Byte *direction_byte = (Byte*)[direction_data bytes];
                    if (direction_byte[0]==0x05) {
                        
//                        NSLog(@"--->05面朝上");
                    }else{
//                        NSLog(@"--->03面朝上");
                    }
                    [mtbDic setObject:@(direction_byte[0]) forKey:device_direction];
                }
                //按钮状态
                if (jude_byte[0]==0x06) {
                    NSData *button_data = [data subdataWithRange:NSMakeRange(11, 1)];
                    Byte *button_byte = (Byte*)[button_data bytes];
                    [mtbDic setObject:@(button_byte[0]) forKey:device_button_state];
                    
                }
            }
        }
        
        //保存数据到偏好设置
        //[kUserDefaults setObject:mtbDic forKey:peripheral.identifier.UUIDString];
        //保存到内存
        [self.deviceInfo setObject:mtbDic forKey:peripheral.identifier.UUIDString];
        
        //信号,蓝牙名,mac等过滤
        [self DeviceFilte:peripheral RSSI:RSSI deviceInfo:mtbDic deviceName:deviceName_str];
    }
    //--------------------------------------------------------------------
    //EddyStone的处理   serviceUUID:FEAA   Google的UUID标识
 else   if ([advertisementData[@"kCBAdvDataServiceData"] objectForKey:[CBUUID UUIDWithString:@"FEAA"]]&&(self.deviceType==DeviceTypeEddystone)) {
        NSLog(@"发现设备:%@ 广播内容:%@  信号强度:%@\n identifer:%@",peripheral.name,advertisementData,RSSI,peripheral.identifier.UUIDString);
        NSData *eddystone_data = [advertisementData[@"kCBAdvDataServiceData"] objectForKey:[CBUUID UUIDWithString:@"FEAA"]];
        NSString *deviceName_str;//蓝牙名称
        NSMutableDictionary *mtbDic ;
        if ([self.deviceInfo objectForKey:peripheral.identifier.UUIDString]) {
            mtbDic = [self.deviceInfo objectForKey:peripheral.identifier.UUIDString];
        }else{
            mtbDic = [NSMutableDictionary new];
        }
        if (advertisementData[@"kCBAdvDataLocalName"]) {
            [mtbDic setObject:advertisementData[@"kCBAdvDataLocalName"] forKey:device_name];
            deviceName_str = [advertisementData[@"kCBAdvDataLocalName"] uppercaseString];
        }else{
            deviceName_str = [peripheral.name uppercaseString];
        }
        if (deviceName_str.length==0) {
            deviceName_str = @"unknow";
        }
        [mtbDic setObject:deviceName_str forKey:device_name];
        [mtbDic setObject:@"Eddystone" forKey:device_type];
        //信号
        [mtbDic setObject:RSSI forKey:device_rssi];
        
        NSData *frame_type_Data = [eddystone_data subdataWithRange:NSMakeRange(0, 1)];
        Byte *frame_type_byte = (Byte*)[frame_type_Data bytes];
        //EddyStone-UID
        if (frame_type_byte[0] == 0x00) {
            [mtbDic setObject:@"UID" forKey:device_Eddystone_type];
            //tx power 第二个字节
            NSData *txPower_Data =  [eddystone_data subdataWithRange:NSMakeRange(1, 1)];
            NSUInteger power = [LBTool convertHexDataToDecimalism:txPower_Data];
            NSString *powerStr = [NSString stringWithFormat:@"%lu",(unsigned long)power];
            [mtbDic setObject:powerStr forKey:device_tx_power];
            //namespace ID 第3-12个字节,共10个字节
            NSData *namespace_Data =  [eddystone_data subdataWithRange:NSMakeRange(2, 10)];
            NSString *namespaceStr = [LBTool convertHexDataToHexString:namespace_Data];
            [mtbDic setObject:namespaceStr forKey:device_UID_NamespaceID];
            //instance ID 第12-17个字节,共6个字节
            NSData *instance_Data =  [eddystone_data subdataWithRange:NSMakeRange(12, 6)];
            NSString *instanceStr = [LBTool convertHexDataToHexString:instance_Data];
            [mtbDic setObject:instanceStr forKey:device_UID_InstanceID];
        }
        //EddyStone-URL
        if (frame_type_byte[0] == 0x10) {
            [mtbDic setObject:@"URL" forKey:device_Eddystone_type];
            //tx power 第二个字节
            NSData *txPower_Data =  [eddystone_data subdataWithRange:NSMakeRange(1, 1)];
            int power = [LBTool convertHexDataToDecimalism:txPower_Data];
            NSString *powerStr = [NSString stringWithFormat:@"%d",power];
            [mtbDic setObject:powerStr forKey:device_tx_power];
            //url前缀 第3个字节
            NSData *URL_type_Data =  [eddystone_data subdataWithRange:NSMakeRange(2, 1)];
            //网址前缀
            NSString *url_preStr = [LBTool getEddyStone_URL_prefix:URL_type_Data];
            //网址内容
            NSData *URL_content_Data =  [eddystone_data subdataWithRange:NSMakeRange(3, eddystone_data.length-5)];
            NSString *url_content = [[NSString alloc]initWithData:URL_content_Data encoding:NSUTF8StringEncoding];
            //网址后缀
            NSData *URL_subfix_Data =  [eddystone_data subdataWithRange:NSMakeRange(eddystone_data.length-1,1)];
            NSString *url_subfix = [LBTool getEddyStone_URL_subfix:URL_subfix_Data];
            NSString *url_finale = [NSString stringWithFormat:@"%@%@%@",url_preStr,url_content,url_subfix];
            [mtbDic setObject:url_finale forKey:device_URL_content];
            
        }
        //EddyStone-TLM
        if (frame_type_byte[0] == 0x20) {
            [mtbDic setObject:@"TLM" forKey:device_Eddystone_type];
            //version
            NSData *TLM_version_Data =  [eddystone_data subdataWithRange:NSMakeRange(1, 1)];
            int version = [LBTool convertHexDataToDecimalism:TLM_version_Data];
            NSString *versionStr = [NSString stringWithFormat:@"%d",version];
            [mtbDic setObject:versionStr forKey:device_TLM_version];
            //temperature  (2个字节)
            //整数部分
            NSData *TLM_temperature_intergralPart_Data =  [eddystone_data subdataWithRange:NSMakeRange(4, 1)];
            int temperature_intergralPart = [LBTool convertHexDataToDecimalism:TLM_temperature_intergralPart_Data];
            //小数部分
            NSData *TLM_temperature_decimalPart_Data =  [eddystone_data subdataWithRange:NSMakeRange(5, 1)];
            int temperature_decimalPart = [LBTool convertHexDataToDecimalism:TLM_temperature_decimalPart_Data];
            NSString *temperatureStr = [NSString stringWithFormat:@"%d.%d",temperature_intergralPart,temperature_decimalPart];
            
            [mtbDic setObject:temperatureStr forKey:device_TLM_temperature];
            
            //Battery voltage (2个字节)
            //整数部分
            NSData *TLM_voltage_intergralPart_Data =  [eddystone_data subdataWithRange:NSMakeRange(2, 2)];
            int voltage_intergralPart = [LBTool convertHexDataToDecimalism:TLM_voltage_intergralPart_Data];
            
            NSString *voltageStr = [NSString stringWithFormat:@"%d",voltage_intergralPart];
            [mtbDic setObject:voltageStr forKey:device_TLM_voltage];
            //Advertising PDU count
            NSData *TLM_PDU_Data =  [eddystone_data subdataWithRange:NSMakeRange(6, 4)];
            int pdu = [LBTool convertHexDataToDecimalism:TLM_PDU_Data];
            NSString *pduStr = [NSString stringWithFormat:@"%d",pdu];
            [mtbDic setObject:pduStr forKey:device_TLM_PDU];
            //Time since power-up
            NSData *TLM_timeSincePowerUp_Data =  [eddystone_data subdataWithRange:NSMakeRange(10, 4)];
            int time = [LBTool convertHexDataToDecimalism:TLM_timeSincePowerUp_Data];
            NSString *timeStr = [NSString stringWithFormat:@"%d",time];
            [mtbDic setObject:timeStr forKey:device_TLM_timeSincePowerUp];
        }
        //EddyStone-EID
        if (frame_type_byte[0] == 0x30) {
            [mtbDic setObject:@"EID" forKey:device_Eddystone_type];
            //txpower
            NSData *txPower_Data =  [eddystone_data subdataWithRange:NSMakeRange(1, 1)];
            int power = [LBTool convertHexDataToDecimalism:txPower_Data];
            NSString *powerStr = [NSString stringWithFormat:@"%d",power];
            [mtbDic setObject:powerStr forKey:device_tx_power];
            //
            NSData *EID_Data =  [eddystone_data subdataWithRange:NSMakeRange(2, eddystone_data.length-2)];
            NSString *EID_id = [LBTool convertHexDataToHexString:EID_Data];
            [mtbDic setObject:EID_id forKey:device_EID_ID];
        }
        //保存到内存
        [self.deviceInfo setObject:mtbDic forKey:peripheral.identifier.UUIDString];
        
        //信号,蓝牙名,mac等过滤
        [self DeviceFilte:peripheral RSSI:RSSI deviceInfo:mtbDic deviceName:deviceName_str];
 }else{
     //-----------------------普通的设备处理 ---------
     NSString *deviceName_str;//蓝牙名称
     NSMutableDictionary *mtbDic ;
     if ([self.deviceInfo objectForKey:peripheral.identifier.UUIDString]) {
         mtbDic = [self.deviceInfo objectForKey:peripheral.identifier.UUIDString];
     }else{
         mtbDic = [NSMutableDictionary new];
     }
     if (advertisementData[@"kCBAdvDataLocalName"]) {
         [mtbDic setObject:advertisementData[@"kCBAdvDataLocalName"] forKey:device_name];
         deviceName_str = [advertisementData[@"kCBAdvDataLocalName"] uppercaseString];
     }else{
         deviceName_str = [peripheral.name uppercaseString];
     }
     if (deviceName_str.length==0) {
         deviceName_str = @"unknow";
     }
     [mtbDic setObject:deviceName_str forKey:device_name];
     [mtbDic setObject:@"Eddystone" forKey:device_type];
     //信号
     [mtbDic setObject:RSSI forKey:device_rssi];
     //保存到内存
     [self.deviceInfo setObject:mtbDic forKey:peripheral.identifier.UUIDString];
     
     //信号,蓝牙名,mac等过滤
     [self DeviceFilte:peripheral RSSI:RSSI deviceInfo:mtbDic deviceName:deviceName_str];
 }
    //--------------------------------------------------------------
    //扫描到设备
    if ([self.delegate respondsToSelector:@selector(bluetoothCenterDidScandPeripheral:)]) {
        [self.delegate bluetoothCenterDidScandPeripheral:peripheral];
    }

}
//信号过滤
-(void)DeviceFilte:(CBPeripheral*)peripheral RSSI:(NSNumber*)RSSI deviceInfo:(NSMutableDictionary*)mtbDic deviceName:(NSString*)deviceName_str
{
    //已经添加过的不处理
    if ([self.peripheralUUIDs containsObject:peripheral.identifier])return;
    BOOL isAdd = YES;
    NSString *filter_str;//过滤的名称
    if (self.filterString) {
        //统一转成大写再进行比较
        filter_str = [self.filterString uppercaseString];
    }
    //大于设定的信号强度值才添加
    if (self.isFilterRSSI) {
        if ([RSSI intValue]<self.rssi_filter) {
            isAdd = NO;
        }
    }
    //mac/设备名  过滤
    if (self.filterString.length>0) {
        isAdd = NO;
        //mac地址比较,把保存的取出来,去掉":",把需要过滤的mac地址去掉":"和"-"
        NSString *mac_string = [[mtbDic objectForKey:device_mac] uppercaseString];  //FD:EA:89:E4:12
        NSString *dispose_mac;//处理":"和"-"字符后
        NSString *dispose_filter;
        //mac过滤
        
        if (mac_string) {
            dispose_mac = [mac_string stringByReplacingOccurrencesOfString:@":" withString:@""];//FDEA89E412
            if ([mac_string containsString:@":"]) {
                dispose_filter = [filter_str stringByReplacingOccurrencesOfString:@":" withString:@""];
            }
            if ([mac_string containsString:@"-"]) {
                dispose_filter = [filter_str stringByReplacingOccurrencesOfString:@"-" withString:@""];
            }
            if ([dispose_mac containsString:dispose_filter]) {
                isAdd = YES;
            }
            
        }
        //设备名过滤
        if ([[deviceName_str uppercaseString] containsString:filter_str]){
            isAdd = YES;
        }
    }
    //major 过滤
    if (self.isFilterMajor) {
        if ([mtbDic objectForKey:device_major]) {
            int majorValue = [[mtbDic objectForKey:device_major]intValue];
            if (majorValue<self.majorMin_filter||majorValue>self.majorMax_filter) {
                isAdd = NO;
            }
        }else{
            isAdd = NO;
        }
        
    }
    //minor 过滤
    if (self.isFilterMinor) {
        if ([mtbDic objectForKey:device_minor]) {
            int minorValue = [[mtbDic objectForKey:device_minor]intValue];
            if (minorValue<self.minorMin_filter||minorValue>self.majorMax_filter) {
                isAdd = NO;
            }
        }else{
            isAdd = NO;
        }
        
    }
    if (isAdd) {
        [self.peripheralUUIDs addObject:peripheral.identifier];
        [self.peripherals addObject:peripheral];
       // [self sortByRSSI];//排序
        
        //添加到数组,刷新设备列表
        if ([self.delegate respondsToSelector:@selector(refreshTableView)]) {
            [self.delegate refreshTableView];
        }
    }
   
    
}

#pragma mark ------- 按信号强度排序
-(void)sortByRSSI
{
    return;
    //对搜索到的设备进行排序
    if (self.peripherals.count>1) {
        NSArray *result = [self.peripherals sortedArrayUsingComparator:^NSComparisonResult(CBPeripheral* obj1, CBPeripheral* obj2) {
            NSDictionary *obj1_dic = [kUserDefaults objectForKey:obj1.identifier.UUIDString];
            NSDictionary *obj2_dic = [kUserDefaults objectForKey:obj2.identifier.UUIDString];
//            NSLog(@"%@==%@",obj1_dic,obj2_dic);
            return [[obj1_dic objectForKey:device_rssi]intValue]<[[obj2_dic objectForKey:device_rssi]intValue];
        }];
        self.peripherals = result.mutableCopy;
    }
}
-(void)startConnectTimer
{
    self.isConnecting = YES;
    if (_connectTimer==nil) {
        _connectTimer = [TempTarget scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCountAction) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop]addTimer:_connectTimer forMode:NSRunLoopCommonModes];
    }
}
-(void)stopConnectTimer
{
    [_connectTimer invalidate];
    _connectTimer = nil;
    connectCount = 0;
    self.isConnecting = NO;
}
-(void)timeCountAction
{
    connectCount++;
    if (connectCount==17) {
        
        
        [self stopConnectTimer];
        if ([self.delegate respondsToSelector:@selector(bluetoothCenterDidFailToConnnectPeripheral)]) {
            [self.delegate bluetoothCenterDidFailToConnnectPeripheral];
        }
        [MBProgressHUD showError:@"Connection timed out!"];
    }
}
#pragma mark ------- 连接外设 ---------
- (void)connetPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"连接蓝牙:%@...",peripheral.name);
    [self startConnectTimer];
    [self stopDisconnectTimer];
    self.currentPeripheral = peripheral;
    //CBConnectPeripheralOptionNotifyOnNotificationKey: 这是一个NSNumber(Boolean)，表示系统会为获得的外设收到通知后显示一个提示，这个时候应用是被挂起的。
    [self.centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnNotificationKey:@(1)}];
//    [self.centralManager stopScan];
}

#pragma mark --------- 已连接外设--->扫描外设中的服务 ----------
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    [self stopConnectTimer];
    [MBProgressHUD dismiss];
    NSLog(@"连接蓝牙成功:%@ UUID:%@",peripheral.name,peripheral.identifier.UUIDString);
    self.isManualDisconnect = NO;
    //停止扫描
    [self.centralManager stopScan];
//    [self stopDisconnectTimer];
    //保存已连接的外设到钥匙串
    [self setConnectedPeripheralIdentifier:peripheral.identifier.UUIDString];
    if (_autoConSuc) {
        _autoConSuc();
    }
    //保存设备
    if (![self.connectSuccessPeripherals containsObject:peripheral]) {
        [self.connectSuccessPeripherals addObject:peripheral];
        if (_peripheralBlk) {
            _peripheralBlk(_connectSuccessPeripherals);
        }
        //连接数量达到两个就停止搜索
        if (self.connectSuccessPeripherals.count>=2) {
            [self.centralManager stopScan];
        }
    }
    if ([self.delegate respondsToSelector:@selector(bluetoothDidConnectedPeripheral:)]) {
        [self.delegate bluetoothDidConnectedPeripheral:peripheral];
    }
    
    self.isConnectPeripheral = YES;
    self.currentPeripheral = peripheral;
    peripheral.delegate = self;
    // 发现服务
    [peripheral discoverServices:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:BluetoochConnectedPeripher object:peripheral];
    
    
}

#pragma mark --------- 发现服务 ----------
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    NSLog(@"发现服务");
    
    for (CBService *service in peripheral.services) {
            [peripheral discoverCharacteristics:nil forService:service];
        
    }
}
#pragma mark --------- 发现服务里的特征 ----------

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"发现服务里面的特征值:%@ UUID:%@  特征属性:%d",[[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding],characteristic.UUID.UUIDString,characteristic.properties);
        if ([characteristic.UUID isEqual:CharacteristicReadUUID]) {
            //订阅特征
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        } else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:self.writeCharacteristics]]) {
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];

        }
//        __weak typeof(self) weakSelf = self;
//        //请输入密码
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"please enter password" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"cannel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            [weakSelf disconnectCurrentPeripheral];
//        }];
//        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            UITextField *textField = alertVC.textFields.lastObject;
//            [weakSelf sendPassWord:textField.text];
////            [weakSelf sendPassWord:@"aa14061112"];
//        }];
//        [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//            textField.placeholder = @"please enter password";
//        }];
//        [alertVC addAction:cancel];
//        [alertVC addAction:sure];
//        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
        
    }
    if ([self.delegate respondsToSelector:@selector(didDiscoverCharacteristicsForService:)]) {
        [self.delegate didDiscoverCharacteristicsForService:peripheral];
    }
}

- (void)stopScand {
        [self.centralManager stopScan];
}
#pragma mark ------- 主动断开连接 ---------
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral {
//    [self setConnectedPeripheralIdentifier:@" "];
    if (peripheral.state == CBPeripheralStateConnected) {
        [self.centralManager cancelPeripheralConnection:peripheral];
    }
    
    [self.centralManager stopScan];
    
}
#pragma mark ------- 主动断开当前最后连接的设备 ---------
-(void)disconnectCurrentPeripheral
{
    if (self.currentPeripheral) {
        
        [self.centralManager cancelPeripheralConnection:self.currentPeripheral];
    }
    
}
#pragma mark ------- 主动断开当前连接的所有设备设备 ---------
-(void)disconnectAllPeripheral
{
    for (CBPeripheral *perpheral in self.connectSuccessPeripherals) {
        [self cancelPeripheralConnection:perpheral];
    }
}
#pragma mark ----- centralManager断开外设回调 -------------
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    
    
    //清除缓存
    if ([self.deviceInfo objectForKey:peripheral.identifier.UUIDString]) {
        [self.deviceInfo removeObjectForKey:peripheral.identifier.UUIDString];
    }
    self.disconnectPeripheral = peripheral;
    //后面加上的,只能用于连接一个设备的情况
    self.isConnectPeripheral = NO;
    
    NSInteger disConnectCount = 0;
    for (NSInteger i = 0 ; i < self.connectSuccessPeripherals.count; i++) {
        CBPeripheral *p = self.connectSuccessPeripherals[i];
        if (p.state == CBPeripheralStateDisconnected) {
            disConnectCount++;
            if (disConnectCount == self.connectSuccessPeripherals.count) {
                self.isConnectPeripheral = NO;
            }
            
        }
    }
//    [self.peripherals removeAllObjects];
//    [self.peripheralUUIDs removeAllObjects];
    //移除
    if ([self.connectSuccessPeripherals containsObject:peripheral]) {
        [self.connectSuccessPeripherals removeObject:peripheral];
        if (_peripheralBlk) {
            _peripheralBlk(_connectSuccessPeripherals);
        }
    }
    
    //[MBProgressHUD showError:@"device disconnected!"];
    if ([self.delegate respondsToSelector:@selector(bluetoothDisConnectPeripheral:)]) {
        [self.delegate bluetoothDisConnectPeripheral:peripheral];
    }
    NSDictionary *dict = @{@"peripheral":peripheral.name?peripheral.name:@""};
    NSLog(@"断开的蓝牙:%@",peripheral.name);
    [[NSNotificationCenter defaultCenter] postNotificationName:BluetoochDisConnectPeripher object:self userInfo:dict];
    
    
   
}

#pragma mark -----  设置已经连接的外设标识符(最后一次连接的那个设备)
- (void)setConnectedPeripheralIdentifier:(NSString *)identifier {
    [[UICKeyChainStore keyChainStore] setString:identifier forKey:@"connectedIdentifier"];
}
#pragma mark ----- 获取已经保存过的外设标识符
- (NSString *)getConnectedPeripheralIdentifier {
    UICKeyChainStore *keyChainStore = [UICKeyChainStore keyChainStore];
    NSString *savedIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:@"connectedIdentifier"];
    if (savedIdentifier) {
        [keyChainStore setString:savedIdentifier forKey:@"connectedIdentifier"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"connectedIdentifier"];
    }
    savedIdentifier = [keyChainStore stringForKey:@"connectedIdentifier"];
    return savedIdentifier;
}
#pragma mark ------ 获取之前搜索过的设备 ---------
- (NSArray *)getSavedScanningUUIDS {
    UICKeyChainStore *keyChainStore = [UICKeyChainStore keyChainStore];
    NSArray *savedUUIDS = [[NSUserDefaults standardUserDefaults] objectForKey:@"SaveScanningUUIDSInPhone"];
    if (savedUUIDS) {
        NSData *uuidData = [NSKeyedArchiver archivedDataWithRootObject:savedUUIDS];
        [keyChainStore setData:uuidData forKey:@"SaveScanningUUIDSInPhone"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SaveScanningUUIDSInPhone"];
    }
    NSData *savedUUIDData = [keyChainStore dataForKey:@"SaveScanningUUIDSInPhone"];
    savedUUIDS = [NSKeyedUnarchiver unarchiveObjectWithData:savedUUIDData];
    return savedUUIDS;
}
- (NSArray *)getSavedReConnectServiceUUIDs {
    NSArray *uuidStrs = [self getSavedScanningUUIDS];
    NSMutableArray *reConnectSeviceUUIDs = nil;
    if (uuidStrs.count > 0) {
        reConnectSeviceUUIDs = [NSMutableArray arrayWithCapacity:uuidStrs.count];
        for (NSString *uuidStr in uuidStrs) {
            [reConnectSeviceUUIDs addObject:[CBUUID UUIDWithString:uuidStr]];
        }
    } else {
        reConnectSeviceUUIDs = [NSMutableArray arrayWithCapacity:2];
        [reConnectSeviceUUIDs addObject:[CBUUID UUIDWithString:SERVICESTRING]];
    }
    return reConnectSeviceUUIDs;
}
#pragma mark -------- 保存已经搜索到的UUID --------
- (void)saveScanningUUIDS:(NSArray *)uuidStrS {
    UICKeyChainStore *keyChainStore = [UICKeyChainStore keyChainStore];
    NSData *uuidData = [NSKeyedArchiver archivedDataWithRootObject:uuidStrS];
    [keyChainStore setData:uuidData forKey:@"SaveScanningUUIDSInPhone"];
}
- (void)startReConnectTimer {
    [self stopDisconnectTimer];
    if (!_disconnectTimer) {
        _disconnectTimer = [TempTarget scheduledTimerWithTimeInterval:2 target:self selector:@selector(reconnectLastPeripheral) userInfo:nil repeats:YES];
    }
}

#pragma mark ------- 根据uuid获取外设 ---------
- (CBPeripheral *)periperalWithUUID:(NSString *)uuid {
    NSUUID *identifier = [[NSUUID alloc] initWithUUIDString:uuid];
    if (identifier==nil) {
        return nil;
    }
    NSArray *periperals = nil;
    
    if (periperals.count > 0) {
        return [periperals objectAtIndex:0];
    } else {
        return nil;
    }
}
#pragma mark ------ 清除已经成功连接的外设 --------
- (void)clearConnectSuccessPeripherals {
    [self.connectSuccessPeripherals removeAllObjects];
}
- (void)stopDisconnectTimer {
    if (_disconnectTimer) {
        [_disconnectTimer invalidate];
        _disconnectTimer = nil;
    }
}
#pragma mark ------- 重连最后一次连接的那个设备 -------
- (void)reconnectLastPeripheral {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if (accessToken.length != 0) {
        [self reConnect];
    }
}
- (void)reConnect {
    NSLog(@"重连.....");
    //之前搜索过的(指定服务的)设备
    NSArray *uuidArray = [self getSavedReConnectServiceUUIDs];
    if (connectedPh != nil) {
        [connectedPh removeAllObjects];
    }
    
    //检索手机系统里已经连接上的设备
    connectedPh = [NSMutableArray arrayWithArray:[self retrieveConnectPeripheral:uuidArray]];
    BOOL isFind = NO;
    if ([connectedPh count] > 0) {
        for (int i = 0 ; i < [connectedPh count]; i++) {
            CBPeripheral *peripheral = [connectedPh objectAtIndex:i];
            NSString *peripheralIdentifier = peripheral.identifier.UUIDString;
            //如果找到了最后一次连接的那个设备
            if ([peripheralIdentifier isEqualToString:[self getConnectedPeripheralIdentifier]]) {
                [self.centralManager connectPeripheral:[connectedPh objectAtIndex:i] options:nil];
                isFind = YES;
                break;
            }
        }
    } else {
        [self stopDisconnectTimer];
    }
    ////手机系统里没有被连接的设备
    if (!isFind) {
        NSString *uuid = [self getConnectedPeripheralIdentifier];
        if (uuid) {
            CBPeripheral *peripheral = [self periperalWithUUID:uuid];
            if (peripheral) {
                [self connetPeripheral:peripheral];
            }
        }
    }
}
#pragma mark ------- 获取已经连接的外设 --------
- (NSArray *)phoneConnectedDevices
{
    NSArray            *uuidArray    = [self getSavedReConnectServiceUUIDs];
    NSMutableArray *connectedPHs  = [NSMutableArray arrayWithArray:[self retrieveConnectPeripheral:uuidArray]];
    return connectedPHs;
}

#pragma mark -------- 检索已经连接过的外设 --------
//重新获取当前手机系统 蓝牙里连接着的设备列表,要寻找的设备，发起本地连接，使得应用与之连接上
- (NSArray *)retrieveConnectPeripheral:(NSArray *)uuidArray {
    NSArray *connectedDevice = nil;
    
        //[self.centralManager retrievePeripheralsWithIdentifiers:@[]];
        connectedDevice = [self.centralManager retrieveConnectedPeripheralsWithServices:uuidArray];
        NSLog(@"检索到的设备:%@",connectedDevice);
        //将已连接的设备添加到成功连接的数组
        for (CBPeripheral *peripheral in connectedDevice) {
            if (![self.connectSuccessPeripherals containsObject:peripheral]&&peripheral.state == CBPeripheralStateConnected) {
                [self.connectSuccessPeripherals addObject:peripheral];
            }
            //如果是断开的
            NSString *key = [NSString stringWithFormat:@"isAutoconnect-%@",peripheral.identifier.UUIDString];
            BOOL isAutoconnect = [kUserDefaults boolForKey:key];
            if (peripheral.state == CBPeripheralStateDisconnected) {
                [self connetPeripheral:peripheral];
                if (!isAutoconnect) {
                    //[self.centralManager cancelPeripheralConnection:peripheral];
                }else{
                    //[self.centralManager cancelPeripheralConnection:peripheral];
                }
                
            }
        }
    
    return connectedDevice;
}
//这个方法是说coreBluetooth为APP提供了一个保留和回复的功能，当APP需要在后台完成蓝牙相关的任务时，这是你第一个调用的方法，用这个方法可以是APP与系统蓝牙进行同步
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict
{
    NSLog(@"将要恢复外设...%@",dict);
    NSArray *peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey];
    for (CBPeripheral *peripheral in peripherals) {
        NSLog(@"检索到的设备:%@",peripheral.identifier.UUIDString);
        //蓝牙中心里去连接
        [self.centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnNotificationKey:@(1)}];
        //添加到已经连接成功数组里
        if (![self.connectSuccessPeripherals containsObject:peripheral]&&peripheral.state == CBPeripheralStateConnected) {
            [self.connectSuccessPeripherals addObject:peripheral];
            NSLog(@"添加进连接成功数组:%@",peripheral.identifier.UUIDString);
        }
        //检查新旧版本
        [self checkVersion];
    }
    
}
//这个返回retrieveConnectedperipherial调用的值，这里面的数组参数包括系统中与其他APP连接的peripheral，当指定实现这个方法时便可以重新连接APP感兴趣的peripheral。
- (void) centralManager:(CBCentralManager *)central didRetrieveConnectedPeripherals:(NSArray *)peripherals
{
    NSLog(@"已经检索到系统设置里连接的蓝牙");
    
}

- (void)setUpReScan {
    [self scanperipheral];
}
#pragma mark ----- 连接失败 -------
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"连接蓝牙失败:%@",error);
    if (_autoConFail) {
        _autoConFail(@"Connect Fail");
    }
    [MBProgressHUD dismiss];
    [MBProgressHUD showError:@"连接失败"];
    [self stopConnectTimer];
}

#pragma mark -------- 发送校验密码 -----
-(void)sendPassWord:(NSString*)password
{
    
    //命令的头部
    Byte headBytes[] = {0xf3,0x00,0xf3,0x06};
    NSData *headData = [[NSData alloc]initWithBytes:headBytes length:sizeof(headBytes)];
    //指令
    NSData *cmdData = [LBTool convertBytesStringToData:password leng:6 fillPosition:FillPositionBehind];
    NSMutableData *finalData = [NSMutableData new];
    [finalData appendData:headData];
    
    [finalData appendData:cmdData];
    //不足六位在 后面 补00
    if (cmdData.length<6) {
        for (int i=0; i<6-cmdData.length; i++) {
            Byte zero[] = {0x00};
            [finalData appendData:[[NSData alloc]initWithBytes:zero length:sizeof(zero)]];
        }
    }
    [self sendDataToDevice:finalData];
    
}

-(void)sendDataToDevice:(NSData*)data
{
    NSLog(@"发送指令:%@",data);
    for (NSInteger i = 0 ; i < self.connectSuccessPeripherals.count; i++) {
       CBPeripheral *p = self.connectSuccessPeripherals[i];
//         NSLog(@"服务个数:%d",p.services.count);
        BOOL isFind =NO;
       for (CBService *s in p.services) {
           for (CBCharacteristic *c in s.characteristics) {
               if ([c.UUID isEqual:[CBUUID UUIDWithString:self.writeCharacteristics]]) {
                   isFind = YES;
                   [p writeValue:data forCharacteristic:c type:CBCharacteristicWriteWithResponse];
               }
           }
       }
        if (isFind == NO) {
            [MBProgressHUD showError:@"没有找到可写的特征UUID"];
        }
    }
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error
{
    [MBProgressHUD showError:@"发送命令失败"];
}


#pragma mark ------- 写数据回调 -----------
- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
             error:(NSError *)error {
    if (error) {
        NSLog(@"---->写数据失败:%@",error);
    } else {
        
        NSData *data = characteristic.value;
        NSString *resultText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"写数据成功:%@ name=%@",resultText,peripheral.name);
        if ([self.delegate respondsToSelector:@selector(writeDataCallBack:)]) {
            [self.delegate writeDataCallBack:resultText];
        }
    }
}

#pragma mark ------ 外设更新了特征 更新特征的value的时候会调用 ----------
// （凡是从蓝牙传过来的数据都要经过这个回调，简单的说这个方法就是你拿数据的唯一方法）
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"外设更新了特征:%@ 二进制数据:%@ UUID:%@, error:%@",[[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding],characteristic.value,characteristic.UUID.UUIDString,error);
   
    [MBProgressHUD dismiss];
    NSData *data = characteristic.value;
    //取出设备信息
    NSMutableDictionary *mtbDic ;
    if ([self.deviceInfo objectForKey:peripheral.identifier.UUIDString]) {
        mtbDic = [self.deviceInfo objectForKey:peripheral.identifier.UUIDString];
    }else{
        mtbDic = [NSMutableDictionary new];
    }
    
    if ((data.length>=4)) {
        Byte  data_bytes[data.length];
        [data getBytes:data_bytes length:data.length];
        //判断头部
        if (data_bytes[0]==0xf3&&data_bytes[2]==0xf3) {
            
            int value = (int)data_bytes[3];
//            if (value==0) {
//                [MBProgressHUD showSuccess:@"Success!"];
//            }else{
//                [MBProgressHUD showSuccess:@"fail!"];
//            }
            //打印对应信息
            [self parseDataWithType:data_bytes value:value];
            //查询当前温度
            if (data_bytes[1]==0x10) {
                //整数部分(有符号字符类型)
                NSData *integer_data = [data subdataWithRange:NSMakeRange(4, 1)];
                Byte *integer_byte = (Byte*)[integer_data bytes];
                NSString *hexStr = [NSString stringWithFormat:@"%x",integer_byte[0]];
                int sign_value = [LBTool convertSignedHexStrToInt:hexStr];
                
                
                //小数部分(无符号字符类型)
                NSData *decimal_data = [data subdataWithRange:NSMakeRange(5, 1)];
                Byte *decimal_byte = (Byte*)[decimal_data bytes];
                NSString *decimal_string = [NSString stringWithFormat:@"%x",decimal_byte[0]];
                unsigned int outVal;
                NSScanner* scanner = [NSScanner scannerWithString:decimal_string];
                [scanner scanHexInt:&outVal];
                NSString *temp = [NSString stringWithFormat:@"%d.%d",sign_value,outVal];
                [mtbDic setObject:temp forKey:device_temperature];
                NSLog(@"----->当前温度:%@",temp);
                if ([self.delegate respondsToSelector:@selector(deviceDidUpdateInfo:)]) {
                    [self.delegate deviceDidUpdateInfo:@{device_temperature:temp}];
                }
            }
            //查询当前气压
            if (data_bytes[1]==0x11){
                NSData *pressure_data = [data subdataWithRange:NSMakeRange(4, 2)];
               int  pressure_int = [LBTool convertHexDataToDecimalism:pressure_data]+80000;
                [mtbDic setObject:@(pressure_int) forKey:device_pressure];
                NSLog(@"----->当前气压:%d",pressure_int);
                if ([self.delegate respondsToSelector:@selector(deviceDidUpdateInfo:)]) {
                    [self.delegate deviceDidUpdateInfo:@{device_pressure:@(pressure_int)}];
                }
            }
            //查询当前湿度
            if (data_bytes[1]==0x12){
                NSData *humidity_data = [data subdataWithRange:NSMakeRange(4,1)];
                int humidity_int = [LBTool convertHexDataToDecimalism:humidity_data];
                [mtbDic setObject:@(humidity_int) forKey:device_humidity];
                NSLog(@"----->当前湿度:%d",humidity_int);
                if ([self.delegate respondsToSelector:@selector(deviceDidUpdateInfo:)]) {
                    [self.delegate deviceDidUpdateInfo:@{device_humidity:@(humidity_int)}];
                }
            }
            //查访20秒是否有振动
            if (data_bytes[1]==0x13){
                NSData *shake_data = [data subdataWithRange:NSMakeRange(4, 2)];
                //Byte *shake_byte = (Byte*)[shake_data bytes];
                Byte shake1[] = {0x55,0x55};
                NSData *shake1_data = [[NSData alloc]initWithBytes:shake1 length:sizeof(shake1)];
                Byte shake2[] = {0x55,0xAA};
                NSData *shake2_data = [[NSData alloc]initWithBytes:shake2 length:sizeof(shake2)];
                Byte shake3[] = {0xAA,0x55};
                NSData *shake3_data = [[NSData alloc]initWithBytes:shake3 length:sizeof(shake3)];
                Byte shake4[] = {0xAA,0xAA};
                NSData *shake4_data = [[NSData alloc]initWithBytes:shake4 length:sizeof(shake4)];
                int type=0;
                if ([shake_data isEqualToData:shake1_data]) {
                    type = 2;
                    NSLog(@"---->静止状态");
                }
                if ([shake_data isEqualToData:shake2_data]) {
                    type = 3;
                    NSLog(@"---->加速度变化触发");
                }
                if ([shake_data isEqualToData:shake3_data]) {
                    type = 4;
                    NSLog(@"----->角加速度变化触发");
                }
                if ([shake_data isEqualToData:shake4_data]) {
                    type = 5;
                    NSLog(@"加速度和角加速度皆变化触发");
                }
                [mtbDic setObject:@(type) forKey:device_shake];
                if ([self.delegate respondsToSelector:@selector(deviceDidUpdateInfo:)]) {
                    [self.delegate deviceDidUpdateInfo:@{device_shake:@(type)}];
                }
            }
            //查访哪个面朝上
            if (data_bytes[1]==0x14){
                NSData *direction_data = [data subdataWithRange:NSMakeRange(4, 1)];
                Byte *direction_byte = (Byte*)[direction_data bytes];
                if (direction_byte[0]==0x05) {
                    
//                        NSLog(@"--->05面朝上");
                }else{
//                        NSLog(@"--->03面朝上");
                }
                [mtbDic setObject:@(direction_byte[0]) forKey:device_direction];
            }
            //按键状态
            if (data_bytes[1]==0x15){
                NSData *button_data = [data subdataWithRange:NSMakeRange(4, 1)];
                Byte *button_byte = (Byte*)[button_data bytes];
                [mtbDic setObject:@(button_byte[0]) forKey:device_button_state];
                
                if ([self.delegate respondsToSelector:@selector(deviceDidUpdateInfo:)]) {
                    [self.delegate deviceDidUpdateInfo:@{device_button_state:@(button_byte[0])}];
                }
            }
            //电量
            if (data_bytes[1]==0x16){
                NSData *button_data = [data subdataWithRange:NSMakeRange(4, 1)];
                Byte *button_byte = (Byte*)[button_data bytes];
                [mtbDic setObject:@(button_byte[0]) forKey:device_battery];
                
                if ([self.delegate respondsToSelector:@selector(deviceDidUpdateInfo:)]) {
                    [self.delegate deviceDidUpdateInfo:@{device_battery:@(button_byte[0])}];
                }
            }
            
            //eddystone 的广播状态
            if (data_bytes[1]==0x30) {
                if (data.length==8) {
                    //截取后面4个字节
                    NSData *state_data = [data subdataWithRange:NSMakeRange(4, 4)];
                    Byte *state_byte = (Byte*)[state_data bytes];
                    NSMutableDictionary *stateDic = [NSMutableDictionary new];
                    [stateDic setObject:@(state_byte[0]) forKey:device_UID_Adv_state];
                    [stateDic setObject:@(state_byte[1]) forKey:device_URL_Adv_state];
                    [stateDic setObject:@(state_byte[2]) forKey:device_TLM_Adv_state];
                    [stateDic setObject:@(state_byte[3]) forKey:device_EID_Adv_state];
                    if ([self.delegate respondsToSelector:@selector(deviceDidUpdateInfo:)]) {
                        [self.delegate deviceDidUpdateInfo:stateDic];
                    }
                }
                
            }
        }
        //保存到内存
        [self.deviceInfo setObject:mtbDic forKey:peripheral.identifier.UUIDString];
    }
    
}
#pragma mark ------- 订阅通知回调 -----------

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
             error:(NSError *)error {
    if (error) {
        NSLog(@"错误信息:%@",error);
        return;
    }
    NSLog(@"订阅通知更新:%@  二进制:%@  UUID:%@",[[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding],characteristic.value,characteristic.UUID.UUIDString);
    
   
    
}
#pragma mark ***********************************************************

-(void)updateRSSIAndBattery
{
    [self.peripherals removeAllObjects];
    [self.peripheralUUIDs removeAllObjects];
    [self.centralManager stopScan];
    [self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(1)}];
}



-(void)startUpdateTimer
{
    [self updateRSSIAndBattery];
    if (readRSIIAndBatteryTimer == nil) {
        [self updateRSSIAndBattery];
        readRSIIAndBatteryTimer = [TempTarget scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateRSSIAndBattery) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:readRSIIAndBatteryTimer forMode:NSRunLoopCommonModes];
    }
}
-(void)stopUpdateTimer{
    
    [readRSIIAndBatteryTimer invalidate];
    readRSIIAndBatteryTimer = nil;
}


#pragma mark ------接收信号强度------------
-(void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error
{
    NSInteger value =  130 - abs([RSSI intValue]);
    if (value >=100 ) {
        value = 99;
    }
    if ([self.delegate respondsToSelector:@selector(receiveRSSI:peripheral:)]&&!error) {
        
        [self.delegate receiveRSSI:[NSString stringWithFormat:@"%zd",value] peripheral:peripheral];
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kReceiveRSSI object:[NSString stringWithFormat:@"%zd",value]];
    
}



- (NSMutableArray<CBPeripheral *> *)peripherals {
    if (!_peripherals) {
        _peripherals = [[NSMutableArray alloc] init];
    }
    return _peripherals;
}
- (NSMutableArray<NSUUID *> *)peripheralUUIDs {
    if (!_peripheralUUIDs) {
        _peripheralUUIDs = [[NSMutableArray alloc] init];
    }
    return _peripheralUUIDs;
}

- (void)disConnectPeripheral:(opSucess)sucess
                      opFail:(opFail)fail {
}

/**
 重连

 @param sucess 成功回调
 @param fail 失败回调
 */
- (void)reConnectOpSucess:(opSucess)sucess opFail:(opFail)fail {
    if (self.connectSuccessPeripherals.count > 0) {
        sucess();
    } else {
        if ([[BluetoothCenter shareInstance] phoneConnectedDevices].count > 0) {
            _autoConSuc = sucess;
            _autoConFail = fail;
            [[BluetoothCenter shareInstance] reConnect];
        } else {
            _autoConSuc = sucess;
            _autoConFail = fail;
            [self startReConnectTimer];
        }
    }
}

@end
